package com.linked.scheduledtasks.util;

import okhttp3.*;
import okio.Buffer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.Map;

@Component
public class OkHttpUtils {


    private final OkHttpClient okHttpClient;

    private final static Logger LOGGER = LoggerFactory.getLogger(OkHttpUtils.class);


    @Autowired
    public OkHttpUtils(OkHttpClient okHttpClient) {
        this.okHttpClient = okHttpClient;
    }

    /**
     * get 请求
     *
     * @param url 请求url地址
     * @return string
     */
    public String doGet(String url) {
        return doGet(url, null, null);
    }


    /**
     * get 请求
     *
     * @param url    请求url地址
     * @param params 请求参数 map
     * @return string
     */
    public String doGet(String url, Map<String, String> params) {
        return doGet(url, params, null);
    }

    /**
     * get 请求
     *
     * @param url     请求url地址
     * @param headers 请求头字段 {k1,v1,k2,v2,...}
     * @return string
     */
    public String doGet(String url, String[] headers) {
        return doGet(url, null, headers);
    }


    /**
     * get 请求
     *
     * @param url     请求url地址
     * @param params  请求参数 map
     * @param headers 请求头字段 {k1,v1,k2,v2,...}
     * @return string
     */
    public String doGet(String url, Map<String, String> params, String[] headers) {
        StringBuilder sb = new StringBuilder(url);
        if (params != null && params.keySet().size() > 0) {
            boolean firstFlag = true;

            for (Map.Entry<String, String> kv : params.entrySet()) {
                if (firstFlag) {
                    sb.append("?").append(kv.getKey()).append("=").append(kv.getValue());
                } else {
                    sb.append("&").append(kv.getKey()).append("=").append(params.get(kv.getValue()));
                }
            }
        }

        Request.Builder builder = new Request.Builder();
        if (headers != null && headers.length > 0) {
            if (headers.length % 2 == 0) {
                for (int i = 0; i < headers.length; i = i + 2) {
                    builder.addHeader(headers[i], headers[i + 1]);
                }
            }
        }

        Request request = builder.url(sb.toString()).build();
        return execute(request);
    }

    /**
     * post 请求
     *
     * @param url    请求url地址
     * @param params 请求参数 map
     * @return string
     */
    public String doPost(String url, Map<String, String> params) {
        FormBody.Builder builder = new FormBody.Builder();

        if (params != null && params.keySet().size() > 0) {

            for (Map.Entry<String, String> kv : params.entrySet()) {
                builder.add(kv.getKey(), kv.getValue());
            }
        }

        Request request = new Request.Builder().url(url).post(builder.build()).build();

        return execute(request);
    }

    public String doPostFile(String url, File file, Map<String, String> params) {

        MultipartBody.Builder builder = new MultipartBody.Builder();
        builder.setType(MultipartBody.FORM);

        //添加参数
        if (params != null) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                builder.addFormDataPart(entry.getKey(), entry.getValue());
            }
        }
        if (file != null) {
            builder.addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("multipart/form-data;"), file));
        }
        RequestBody requestBody = builder.build();
        Request request = new Request.Builder().url(url).post(requestBody).build();
        return execute(request);
    }

    public Request.Builder getRequestBuilder(Map<String, String> headers){
        Request.Builder builder = new Request.Builder();
        if(headers != null){
            for (Map.Entry<String,String> item : headers.entrySet()){
                builder.addHeader(item.getKey(), item.getValue());
            }
        }
        return builder;
    }


    public String doPost(String url, Map<String, String> params, Map<String, String> headers) {

        Headers.Builder okHeadersBuilder = new Headers.Builder();
        okHeadersBuilder.add("code", headers.get("code"));

        FormBody.Builder builder = new FormBody.Builder();

        if (params != null && params.keySet().size() > 0) {

            for (Map.Entry<String, String> kv : params.entrySet()) {
                builder.add(kv.getKey(), kv.getValue());
            }
        }

        Request request = new Request.Builder().url(url).headers(okHeadersBuilder.build()).post(builder.build()).build();

        return execute(request);
    }

    /**
     * post 请求, 请求数据为 json 的字符串
     *
     * @param url  请求url地址
     * @param json 请求数据, json 字符串
     * @return string
     */
    public String doPostJson(String url, String json) {
        return exectePost(url, json, MediaType.parse("application/json; charset=utf-8"));
    }

    public String doPostJson(String url, Map<String, String> headers, String json) {
        return exectePost(url, json, MediaType.parse("application/json; charset=utf-8"), headers);
    }

    /**
     * post 请求, 请求数据为 xml 的字符串
     *
     * @param url 请求url地址
     * @param xml 请求数据, xml 字符串
     * @return string
     */
    public String doPostXml(String url, String xml) {
        return exectePost(url, xml, MediaType.parse("application/xml; charset=utf-8"));
    }

    /**
     * 执行post请求
     *
     * @param url         请求url
     * @param data        请求数据
     * @param contentType 数据类型
     * @return string
     */
    private String exectePost(String url, String data, MediaType contentType) {
        RequestBody requestBody = RequestBody.create(contentType, data);
        Request request = new Request.Builder().url(url).post(requestBody).build();
        return execute(request);
    }


    /**
     * 执行post请求
     *
     * @param url         请求url
     * @param data        请求数据
     * @param contentType 数据类型
     * @param headers     headers
     * @return string
     */
    private String exectePost(String url, String data, MediaType contentType, Map<String, String> headers) {
        Headers.Builder okHeadersBuilder = new Headers.Builder();
        okHeadersBuilder.add("code", headers.get("cczlyy"));
        RequestBody requestBody = RequestBody.create(contentType, data);
        Request request = new Request.Builder().url(url).post(requestBody)
                .headers(okHeadersBuilder.build())
                .build();
        String returnStr = execute(request);

        return returnStr;
    }


    /**
     * 具体执行结果
     *
     * @param request 参数
     * @return String
     */
    private String execute(Request request) {
        Response response = null;
        try {
            response = okHttpClient.newCall(request).execute();
            LOGGER.info("请求结果为：{}", response.toString());
            if (200 != response.code()) {
                String body = "";
                if (ObjectUtils.isEmpty(request.body()) && 0 < request.body().contentLength()) {
                    Buffer buffer = new Buffer();
                    request.body().writeTo(buffer);
                    body = buffer.readString(StandardCharsets.UTF_8);
                    buffer.close();
                }

                LinkedHashMap<String, Object> record = new LinkedHashMap<>();
                record.put("HTTP_CODE", response.code());
                record.put("HTTP_METHOD", response.request().method());
                record.put("HTTP_URL", response.request().url().url().toString());
                record.put("HTTP_URL_PARAMS", response.request().url().query());
                record.put("HTTP_RQ_BODY", body);
            }
            if (response.isSuccessful()) {
                return response.body().string();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return "";
    }
}
